package com.example.baselibrary.utlis

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.SystemClock
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.example.baselibrary.receivers.BootReceiver
import com.example.baselibrary.receivers.RestartReceiver

/**
 * 应用重启工具类（支持延迟重启和开机自启）
 */
object RestartHelper {
    // 广播Action定义
     val ACTION_RESTART = "com.your.package.ACTION_RESTART"
     val ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"
    private const val REQUEST_CODE_RESTART = 1001
    private const val REQUEST_CODE_BOOT = 1002

    /**
     * 安排延迟重启
     * @param context Context
     * @param delayMillis 延迟时间（毫秒）
     * @param reason 重启原因（用于日志统计）
     * @param showToast 是否显示Toast提示
     */
    fun scheduleDelayedRestart(
        context: Context,
        delayMillis: Long,
        reason: String = "UNKNOWN",
        showToast: Boolean = true
    ) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, RestartReceiver::class.java).apply {
            action = ACTION_RESTART
            putExtra("REASON", reason)
        }

        val pendingIntent = PendingIntent.getBroadcast(
            context,
            REQUEST_CODE_RESTART,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or getImmutableFlag()
        )

        // 根据版本选择最佳定时方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + delayMillis,
                pendingIntent
            )
        } else {
            alarmManager.setExact(
                AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + delayMillis,
                pendingIntent
            )
        }

        if (showToast) {
            Toast.makeText(
                context,
                "应用将在${delayMillis / 1000}秒后自动重启",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    /**
     * 取消计划中的重启
     */
    fun cancelScheduledRestart(context: Context) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, RestartReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            context,
            REQUEST_CODE_RESTART,
            intent,
            PendingIntent.FLAG_NO_CREATE or getImmutableFlag()
        )
        pendingIntent?.let {
            alarmManager.cancel(it)
            it.cancel()
        }
    }

    /**
     * 安排开机自启动（需RECEIVE_BOOT_COMPLETED权限）
     */
    fun scheduleBootStart(context: Context) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, BootReceiver::class.java).apply {
            action = ACTION_BOOT
        }

        val pendingIntent = PendingIntent.getBroadcast(
            context,
            REQUEST_CODE_BOOT,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or getImmutableFlag()
        )

        // 使用setAlarmClock确保在国产ROM上也能触发
        alarmManager.setAlarmClock(
            AlarmManager.AlarmClockInfo(
                System.currentTimeMillis() + 10_000, // 10秒后启动
                pendingIntent
            ),
            pendingIntent
        )
    }

    /**
     * 立即重启应用（模拟冷启动）
     */
    fun restartImmediately(context: Context) {
        val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            putExtra("RESTARTED", true)
        }
        context.startActivity(intent)

        // 结束当前进程
        android.os.Process.killProcess(android.os.Process.myPid())
    }

    /**
     * 处理PendingIntent的兼容性标志
     */
    private fun getImmutableFlag(): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_IMMUTABLE
        } else {
            0
        }
    }

    /**
     * 检查是否支持开机自启
     */
    fun isBootStartSupported(context: Context): Boolean {
        return context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK).not()
    }
}